package com.upcode.weighing.admin.controller.sys;

import com.upcode.weighing.base.controller.BaseController;
import com.upcode.weighing.domain.SysDetail;
import com.upcode.weighing.domain.SysEditVo;
import com.upcode.weighing.domain.SysRes;
import com.upcode.weighing.domain.SysUser;
import com.upcode.weighing.log.OpsLog;
import com.upcode.weighing.service.SysResService;
import com.upcode.weighing.service.SysUserService;
import com.upcode.weighing.util.SecurityUtils;
import com.upcode.weighing.util.SensitiveInfoUtils;
import com.upcode.weighing.vo.add.SysUserAddVo;
import com.upcode.weighing.vo.del.BaseDelVo;
import com.upcode.weighing.vo.req.PageReqVo;
import com.upcode.weighing.vo.req.pc.client.TuoMinRrturnVo;
import com.upcode.weighing.vo.req.pc.client.TuoMinVo;
import com.upcode.weighing.vo.req.pc.sys.UpdatePWDVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.upcode.weighing.common.constant.BillConstants.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author alex
 * @since 2019-03-10
 */
@RestController
@RequestMapping("/user")
@Api(value = "/user", description = "用户接口", produces = MediaType.ALL_VALUE,tags = {"用户接口"})
public class SysUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    SysUserService sysUserService;
    @Autowired
    private SysResService sysResService;
    @OpsLog(operation = "用户接口/根据登录名获取用户角色/查询" ,type = 1)
    @PostMapping("/getRes")
    @ApiOperation(value = "根据登录名获取用户角色", notes = "查询", httpMethod = "POST")
    public Object getRes(){
        String loginName= SecurityUtils.getCurrentUserUsername();
        List<SysRes> list=sysUserService.getResByLoginName(loginName);
//        List<LxUserRole> list1=sysUserService.getRoleByLoginName(loginName);
        Map m=new HashMap();
       /* //超级管理员获取所有的菜单
        for(int i=0;i<list1.size();i++){
            if(list1.get(i).getNema2().equals("超级管理员")){
                //如果是超级管理员，则具有所有权限
                m.put("data",sysResService.getRes());
                m.put("permission",sysUserService.getAdminPer());
                m.put("roleName",list1.get(i).getNema2());
                return success(m);
            }
        }*/
        m.put("data",list);
        m.put("permission",sysUserService.getResByParam(loginName));
//        m.put("roleName",list1.get(0).getNema2());
        return success(m);
    }

    /**
     * 新增系统账号
     */
    @OpsLog(operation = "用户接口/添加用户/新增" ,type = 2)
    @PostMapping("/add")
    @ApiOperation(value = "添加用户", notes = "添加", httpMethod = "POST")
    public Object add(@Validated @RequestBody SysUserAddVo vo) {
        if (sysUserService.checkLoginId(vo.getLoginName()) > 0) {
            return error("该账号已存在!");
        }

        if (sysUserService.saveInfo(vo)) {
            return success("操作成功!");
        } else {
            return error("操作失败!");
        }
    }
    /**
     * 获取用户分页列表
     */
    @OpsLog(operation = "用户接口/账号管理/查询" ,type = 1)
    @PostMapping("/list")
    @ApiOperation(value = "账号管理",notes = "")
    public Object list(@RequestBody PageReqVo<SysDetail> vo){
        return success(sysUserService.list(vo));
    }
    /**、
     *查询账号详情
     */
    //@OpsLog(operation = "用户接口/查询账号详情/查询" ,type = 1)
    @GetMapping("/details/{userId}")
    @ApiOperation(value = "查询账号详情" , notes = "")
    public Object details(@PathVariable("userId")@NotNull(message = "userId 不能为空") Long userId){
        SysDetail byUserId = sysUserService.getByUserId(userId);
        byUserId.setCard(SensitiveInfoUtils.sensitiveIdCard(byUserId.getCard()));
        byUserId.setTelephone(SensitiveInfoUtils.sensitiveTel(byUserId.getTelephone()));
        if ("".equals(byUserId.getCard())){
            byUserId.setCard("暂未设置");
        }
        if ("".equals(byUserId.getTelephone())){
            byUserId.setTelephone("暂未设置");
        }
        if (null==byUserId){
            return error("没有查询到该账号信息");
        }
        return success(byUserId,"查询成功");
    }

    /**
     * 根据id修改信息
     */
    @OpsLog(operation = "用户接口/账号信息修改/修改" ,type = 4)
    @PostMapping("/update")
    @ApiOperation(value = "账号信息修改" ,notes = "")
    public Object update(@Validated @RequestBody SysEditVo vo){
        try {
            if(!sysUserService.updateByUserId(vo)){
                return error("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
        return success("修改成功");
    }

    /**
     * 初始化账号密码
     * 冻结账号
     */
    @OpsLog(operation = "用户接口/初始化 冻结账号/修改" ,type = 4)
    @PutMapping("/freeze")
    @ApiOperation(value = "初始化 冻结账号" ,notes = "")
    public Object freeze(@Validated @RequestBody SysEditVo vo){
        try {
            if (ACCOUNT_STATUS_FREEZE.equals(vo.getType())){//初始化密码
                if(sysUserService.initializePWD(vo)){
                    return success("初始化密码成功");
                }
            }
            if (ACCOUNT_STATUS_START.equals(vo.getType())){//冻结账号
                if(sysUserService.freeze(vo)) {
                    return success("冻结账号成功");
                }
            }
            if (ACCOUNT_STATUS_CHUSHIHUAPWD.equals(vo.getType())){//启用账号
                if(sysUserService.startStatus(vo)) {
                    return success("启用账号成功");
                }
            }
            return error("失败");
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }

    }

    /**
     * 删除账号
     */
    @OpsLog(operation = "用户接口/删除账号/删除" ,type = 3)
    @ApiOperation(value = "删除账号", notes = "")
    @PostMapping("/delete")
    public Object delete(@RequestBody BaseDelVo vo) {
        try {
            boolean flag=sysUserService.updateStatus(vo);
            if(flag){
                return success("删除成功");
            }
            return error("删除用户失败");
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }
    @OpsLog(operation = "用户管理/脱敏/查询" ,type = 1)
    @PostMapping("/tuomin")
    @ApiOperation(value = "用户脱敏查询")
   /* @ApiImplicitParams(
            {       @ApiImplicitParam(value = "项目id" ,name = "id",required=true),
                    @ApiImplicitParam(value = "1手机  2身份证" ,name = "type",required=true),
            }
    )*/
    public Object tuomin(@RequestBody TuoMinVo vo){
        TuoMinRrturnVo tr = new TuoMinRrturnVo();
        SysDetail byUserId = sysUserService.getByUserId(vo.getId());
        if (1==vo.getType()){
            tr.setValue2(SensitiveInfoUtils.sensitiveTel(byUserId.getTelephone()));
            tr.setValue1(byUserId.getTelephone());
        }
        if (2==vo.getType()){
            tr.setValue2(SensitiveInfoUtils.sensitiveIdCard(byUserId.getCard()));
            tr.setValue1(byUserId.getCard());
        }
        return success(tr);
    }

    @ApiOperation(value = "修改密码",notes ="")
    @PostMapping(value = "/updatePwd")
    public Object updatePwd(@Validated @RequestBody UpdatePWDVo vo) {
        if (!vo.getNewPWD().equals(vo.getNewResPWD())){
            return error("输入的新密码两次不一样 请重新输入");
        }
        SysUser user = sysUserService.getById(SecurityUtils.getCurrentUserId());
        boolean checkOld = new BCryptPasswordEncoder().matches(vo.getOldPWD(),user.getPwd());
        if (!checkOld){
            return error("旧密码输入不正确");
        }
        boolean checkNew = new BCryptPasswordEncoder().matches(vo.getNewPWD(),user.getPwd());
        if(checkNew){
            return error("旧密码和新密码相同");
        }
        user.setPwd(new BCryptPasswordEncoder().encode(vo.getNewPWD()));
        if(sysUserService.updateByPWD(user)>0){
            return success("密码修改成功");
        }
        return error("密码修改失败");
    }

}
